<template>
  <layout v-loading="loading">
    <div class="cart bw">
      <div class="w pad-20-0">
        <div class="pad-20-0 clearfix">
          <div class="fl">
            <router-link :to="{ name: 'index' }">
              <el-image style="width: 134px; height: 42px" src="/images/logo.png" />
            </router-link>
          </div>
          <div class="fr">
            <el-input size="small" placeholder="请输入搜索内容" v-model="keyword" class="input-with-select"
              @keyup.enter="searchEvent">
              <template #append>
                <el-button @click="searchEvent">搜索</el-button>
              </template>
            </el-input>
          </div>
        </div>
        <!-- 购物车商品列表 -->
        <div class="cart-table">
          <el-table 
            ref="tableRef"
            :data="cart.itemList"
            @select="triggerSelectionEvent"
            @select-all="triggerSelectionAllEvent"
            element-loading-text="拼命加载中"
            :header-cell-style="{ background: '#f8f8f8', color: '#999' }">
            <el-table-column type="selection" width="75" align="center" />
            <el-table-column prop="image" align="center" width="90" label="商品">
              <template #default="scope">
                <router-link target="_blank" :to="`/item/${scope.row.id}`">
                  <el-image style="width: 80px; height: 80px" fit="fill" :src="scope.row.image" />
                </router-link>
              </template>
            </el-table-column>
            <el-table-column prop="title" header-align="left" align="left">
              <template #default="scope">
                <router-link class="ct-title" target="_blank" :to="`/item/${scope.row.id}`">
                  {{ scope.row.title }}
                </router-link>
              </template>
            </el-table-column>
            <el-table-column prop="attrs" header-align="left" align="left" width="140" show-overflow-tooltip>
              <template #default="scope">
                <div v-for="(attr, idx) in scope.row.attrs" :key="idx">
                  {{ attr }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="price" header-align="right" align="right" width="120" label="单价">
              <template #default="scope">
                <span>{{ amountCNYFormatter(scope.row.price) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="count" align="center" width="148" label="数量">
              <template #default="scope">
                <el-input-number v-model="scope.row.count" style="width: 99px" size="small" :min="1" :step="1" @change="changeCountEvent(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column prop="amount" header-align="right" align="right" width="140" label="小计">
              <template #default="scope">
                <strong>{{ amountCNYFormatter(scope.row.amount) }}</strong>
              </template>
            </el-table-column>
            <el-table-column fixed="right" align="center" width="100" label="操作">
              <template #default="scope">
                <el-link @click="deleteEvent(scope.row)" :underline="false">删除</el-link>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 最下面工具栏：批量操作、结算 -->
        <div class="pad-20-0">
          <el-affix position="bottom" :offset="5" :z-index="99999">
            <div class="cart-floatbar clearfix">
              <div class="fl check-all">
                <el-checkbox v-model="checkAll.checked" :indeterminate="checkAll.indeterminate" label="全选" @click="toggleAllSelectionEvent"></el-checkbox>
              </div>
              <div class="fl check-delete">
                <el-link @click="deleteSelectionEvent" :underline="false">删除选中的商品</el-link>
              </div>
              <el-button class="fr settlement" type="danger" @click="toOrderPage">
                去结算
              </el-button>
              <div class="fr price-sum">
                <span>已选择&nbsp;<span class="red">{{ cart.checkedQuantity }}</span>&nbsp;件商品</span>
                <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
                <span>
                  总价：
                  <span class="price red fs16">
                    <strong>{{ amountCNYFormatter(cart.amount) }}</strong>
                  </span>
                </span>
              </div>
            </div>
          </el-affix>
        </div>
      </div>
    </div>
  </layout>
</template>
<script lang="ts" setup>
import "@/assets/scss/modules/cart.scss";
import { ElTable, ElMessageBox } from "element-plus";
import Layout from "@/views/commons/layout/index.vue";

import http from "@/utils/httpRequest";
import { amountCNYFormatter } from "@/utils";
import { useRouter } from "vue-router";
import { ref, reactive, onMounted, nextTick } from "vue";
import { fa } from "element-plus/es/locale";

const router = useRouter();

// 数据加载状态
const loading = ref(true);

// 购物车数据
const cart = reactive({
  amount: 0,
  itemList: [],
  checkedQuantity: 0,
});

// 检索关键字
const keyword = ref("");

// 全选相关
const checkAll = reactive({
  checked: false,
  indeterminate: false,
});

// 列表引用
const tableRef = ref<InstanceType<typeof ElTable>>()

// 组件挂载完成后执行
onMounted(() => {
  loadCartData();
});

// 加载购物车数据
const loadCartData = () => {
  loading.value = true;
  http
    .post({
      url: "/cart/info",
    })
    .then(async ({ data }) => {
      if (http.success(data, false)) {
        // 数据回显
        let body = data.body;
        cart.amount = body.amount;
        cart.itemList = body.itemList;
        await nextTick();
        // 默认勾选
        cart.itemList.forEach(item => {
          if(item.checked) {
            tableRef.value.toggleRowSelection(item, true);
          }
        });
        // 判断是否全选
        let selectedList = cart.itemList.filter(item => item.checked);
        let selectedSize = selectedList.length;
        checkAll.checked = selectedSize === cart.itemList.length;
        checkAll.indeterminate = selectedSize > 0 && selectedSize < cart.itemList.length;
        // 统计已选中商品件数
        cart.checkedQuantity = selectedSize > 0 ? selectedList.map(item => item.count).reduce((a, b) => a + b) : 0;
      }
      loading.value = false;
    });
};

// 修改商品数量触发的事件
const changeCountEvent = (row) => {
  http
    .post({
      url: "/cart/count",
      data: {
        "skuId": row.id,
        "count": row.count
      }
    })
    .then(({ data }) => {
      if (http.success(data)) {
        loadCartData();
      }
    });
};

// 删除商品事件
const deleteEvent = (row) => {
  deleteCartItemBySkuIds([row.id]);
};

// 删除选中数据
const deleteSelectionEvent = () => {
  // 获取选中数据
  let rows  = tableRef.value.getSelectionRows();
  if (rows.length === 0) {
    return;
  }
  // 执行删除
  let skuIds = rows.map(item => item.id);
  deleteCartItemBySkuIds(skuIds);
};

// 按照 skuId 集合删除购物车
const deleteCartItemBySkuIds = (skuIds) => {
  ElMessageBox
    .confirm(`确定要进行删除吗?`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(() => {
      http
        .instance({
          url: http.adornUrl('/cart/delete'),
          method: "post",
          data: http.adornData(skuIds, false),
        })
        .then(({ data }) => {
          if (http.success(data)) {
            loadCartData();
          }
        });
    })
    .catch(()=>{});
};

// 全选、取消全选操作
const toggleAllSelectionEvent = () => {
  tableRef.value.toggleAllSelection();
}

// 触发选中事件
const triggerSelectionEvent = (selection, row) => {
  let checked = selection.filter(item => item.id === row.id).length > 0;
  checkedHandle([row.id], checked);
}

// 触发全部选中或者全部取消
const triggerSelectionAllEvent = (selection) => {
  // 全部取消勾选
  if (selection.length === 0) {
    let skuIds = cart.itemList.filter(item => item.checked).map(item => item.id);
    checkedHandle(skuIds, false);
    return;
  }
  // 全部勾选
  let skuIds = cart.itemList.filter(item => !item.checked).map(item => item.id);
  checkedHandle(skuIds, true);
}

// 选中处理
const checkedHandle = (skuIds, checked) => {
  http
    .post({
      url: "/cart/checked",
      data: {
        "skuIds": skuIds,
        "checked": checked
      }
    })
    .then(({ data }) => {
      if (http.success(data)) {
        loadCartData();
      }
    });
};

// 查询事件处理
const searchEvent = () => {
  router.push({
    name: "search",
    query: {
      keyword: keyword.value,
    },
  });
};

// 跳转订单页面
const toOrderPage = () => {
  router.push({ name: "order", });
};
</script>
